<?php 
namespace app\wework\model\user\label;
use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;

/**
* 标签 model类
**/
class TagModel
{
	/**
	 * 标签列表
	 * @return 
	 */
	static public function list($name=''){
		$wid = Session::get('wid');
		$res = Db::table('kt_wework_taggroup')
			   	 ->alias('g')
			   	 ->field('g.group_id,group_name,g.web_order')
			   	 ->join('kt_wework_tag t', "g.group_id=t.group_id")
			   	 ->where('g.wid',$wid)
			   	 ->where('t.deleted',1);
		if($name) $res= $res->where('g.group_name','like',"%{$name}%");
			$res = $res->group('group_id')
				 ->order('g.web_order','desc')
				 ->filter(function($group)use($wid,$name){
				 	$where[] = ['wid','=',$wid];
				 	$where[] = ['deleted','=',1];
				 	if($name) $where[] = ['tag_name','like',"%$name%"];
					$group['tag'] = Db::table('kt_wework_tag')->field('tag_id,tag_name,web_order')->where('group_id',$group['group_id'])->where($where)->order('web_order','DESC')->select();
					return $group;
				 })
				 ->select();
		return $res;
	}
	/**
	 * 标签组详情
	 * @param  $groupId  分组id
	 * @return 
	 */
	static public function detailGroup($groupId){
		$wid = Session::get('wid');
		$res = Db::table('kt_wework_taggroup')->field('wid,group_id,group_name,web_order')->where('wid',$wid)->where('group_id',$groupId)
			->filter(function($g){
				$g['tag'] = Db::table('kt_wework_tag')->field('tag_id,tag_name,web_order')->where(['wid'=>$g["wid"],'group_id'=>$g['group_id'],'deleted'=>1])->order('web_order','desc')->select()->toArray();
				return $g;
			})
			->find();
		return $res;
	}
	/**
	 * 标签组上下移动
     * @param  $type up 上移  down下移
     * @param  $groupId  分组id
	 * @return 
	 */
	static public function exchageWeborder($type,$groupId){
		$wid = Session::get('wid');
		$data = [];
		$group = Db::table('kt_wework_taggroup')->where('group_id',$groupId)->find();
		switch ($type) {
			case 'up':  //上移
				$groupExchagne = Db::table('kt_wework_taggroup')->where('web_order','>',$group['web_order'])->where(['wid'=>$wid,'deleted'=>1])->order('web_order','asc')->limit(1)->select();
				if($groupExchagne->isEmpty()) return '已是最上层';
				break;
			case 'down': //下移
				$groupExchagne = Db::table('kt_wework_taggroup')->where('web_order','<',$group['web_order'])->where(['wid'=>$wid,'deleted'=>1])->order('web_order','desc')->limit(1)->select();
				if($groupExchagne->isEmpty()) return '已是最下层';
				break;
		}
		Db::table('kt_wework_taggroup')->update(['id'=>$group['id'],'web_order'=>$groupExchagne[0]['web_order']]);
		Db::table('kt_wework_taggroup')->update(['id'=>$groupExchagne[0]['id'],'web_order'=>$group['web_order']]);
		return 'ok';
	}

	/**
	 * 添加标签
	 * @param $groupId 标签组Id
	 * @param $tagName string  标签名
	 * @return 
	 */
	static public function addTag($groupId,$tagName){
		$wid = Session::get('wid');
		$checkRes = self::checkName(1,$tagName,$groupId);
		if(!$checkRes) return '标签已存在';
		$param =[];
		$param['group_id'] = $groupId;
		$order = Db::table('kt_wework_tag')->where(['wid'=>$wid,'group_id'=>$groupId])->max('web_order');
		$param['tag'] = ['name'=>$tagName,'order'=>$order+1];
		$res = QyWechatApi::addCorpTag($param);
		if($res["errcode"] == "40071") return "标签名字已经存在";
		if($res['errcode'] != 0) return '添加失败';
		if(count($res['tag_group']['tag']) == 0) return 'ok';
		Db::table('kt_wework_tag')->insert(
			[
				'wid'=>$wid,
				'group_id'=>$groupId,
				'tag_id'=>$res['tag_group']['tag'][0]['id'],
				'tag_name'=>$tagName,
				'deleted'=>1,
				'order'=>$res['tag_group']['tag'][0]['order'],
				'create_time'=>date("Y-m-d H:i:s",$res['tag_group']['tag'][0]['create_time']),
				'web_order'=>$res['tag_group']['tag'][0]['order'],
			]
		);
		return 'ok';
	}
	/**
	 * 添加标签组
	 * @param $groupName 标签组名称
	 * @param $tagName array 标签名称
	 * @return 
	 */
	static public function addGroup($groupName,$tagName){
		$wid = Session::get('wid');
		$checkRes = self::checkName(2,$groupName);
		if(!$checkRes) return '标签组已存在';
		$param = [];
		$param['group_name'] = $groupName;
		$i=0;
		$tag = array_map(function($name)use(&$i){
			$i++;
			return ['name'=>$name,['order'=>$i]];
		},$tagName);
		$param['tag'] = $tag;
		$res = QyWechatApi::addCorpTag($param);
		if($res['errcode'] != 0) return '同步失败';
		$maxGroupWeborder = Db::table('kt_wework_taggroup')->where('wid',$wid)->max('web_order');
		Db::table('kt_wework_taggroup')->insert([
			'wid'=>$wid,
			'group_id'=>$res['tag_group']['group_id'],
			'group_name'=>$res['tag_group']['group_name'],
			'deleted'=>1,
			'order'=>$res['tag_group']['order'],
			'create_time'=>date("Y-m-d H:i:s",$res['tag_group']['create_time']),
			'web_order'=>$maxGroupWeborder+1
		]);
		$group_id = $res['tag_group']['group_id'];
		$tagData = array_map(function($tag)use($wid,$group_id){
			return [
				'wid'=>$wid,
				'group_id'=>$group_id,
				'tag_id'=>$tag['id'],
				'tag_name'=>$tag['name'],
				'deleted'=>1,
				'order'=>$tag['order'],
				'create_time'=>date("Y-m-d H:i:s",$tag['create_time']),
				'web_order'=>$tag['order'],
			];
		},$res['tag_group']['tag']);
		Db::table('kt_wework_tag')->insertAll($tagData);
		return 'ok';
	}
	/**
	 * 修改标签组
	 * @param $groupName 标签组名称
	 * @param $groupName  标签组名称
	 * @param $tag array 标签名称
	 * @return 
	 */
	static public function updateGroup($groupId,$groupName,$tag,$removetTag){
		$wid = Session::get('wid');
		$group = Db::table('kt_wework_taggroup')->where('wid',$wid)->where('group_id',$groupId)->find();
		if($groupName!=$group['group_name']){
			$param = [
				'id'=>$groupId,
				'name'=>$groupName
			];
			$editGroup =  QyWechatApi::editCorpTag($param);
			if($editGroup['errcode']==0) Db::table('kt_wework_taggroup')->update(['id'=>$group['id'],'group_name'=>$groupName]);
		}
		if($removetTag){
			$param = [
				'tag_id'=>$removetTag,
			];
			$delTag =  QyWechatApi::delCorpTag($param);
			if($delTag['errcode']==0) Db::table('kt_wework_tag')->where(['wid'=>$wid,'group_id'=>$groupId,'tag_id'=>$removetTag])->update(['deleted'=>0]);
		}
		$addTag = [];
		foreach ($tag as $k => $t) {
			if(!isset($t['tag_id']) || !$t['tag_id']){
				$addTag[]=['name'=>$t['tag_name'],'order'=>$k+1];
			}else{
				$tagInfo = Db::table('kt_wework_tag')->where(['wid'=>$wid,'group_id'=>$groupId,'tag_id'=>$t['tag_id']])->find();
				if($tagInfo["tag_name"] == $t["tag_name"])continue;
				$param = [
					'id'=>$t["tag_id"],
					'name'=>$t["tag_name"]
				];
				$editGroup =  QyWechatApi::editCorpTag($param);
				if($editGroup['errcode']==0)Db::table('kt_wework_tag')->update(['id'=>$tagInfo['id'],'tag_name'=>$t["tag_name"]]);
			}
		}
		if($addTag){
			$param=[];
			$param['group_id']=$groupId;
			$param['tag']=$addTag;
			$addCorpTag = QyWechatApi::addCorpTag($param);
			if($addCorpTag['errcode']==0){
				foreach ($addCorpTag['tag_group']['tag'] as $ta) {
					Db::table('kt_wework_tag')->insert([
						'wid'=>$wid,
						'group_id'=>$groupId,
						'tag_id'=>$ta['id'],
						'tag_name'=>$ta['name'],
						'deleted'=>1,
						'order'=>$ta['order'],
						'create_time'=>date("Y-m-d H:i:s",$ta['create_time']),
						'web_order'=>$ta['order'],
					]);
				}
			}
		}

		return 'ok';

	} 
	/**
	 * 删除标签组
     * @param  $groupId  分组id
	 * @return 
	 */
	static public function deleteGroup($groupId){
		$wid = Session::get('wid');
		$param = [];
		$param['group_id'] = [$groupId];
		$res = QyWechatApi::delCorpTag($param);
		if($res['errcode'] != 0) return '删除失败';
		Db::table('kt_wework_taggroup')->where('wid',$wid)->where('group_id',$groupId)->update(['deleted'=>0]);
		Db::table('kt_wework_tag')->where('wid',$wid)->where('group_id',$groupId)->update(['deleted'=>0]);
		return 'ok';
	}
	/**
	 * @param $name 标签名称
	 * @param $type 1:标签组 2:标签
	 * @param $group_id 标签类型时标签组id
	 * @return 
	 */
	static public function checkName($type,$name,$group_id=''){
		$wid = Session::get('wid');
		$check = true;
		switch ($type) {
			case '1':
				$res = Db::table('kt_wework_taggroup')->where(['wid'=>$wid,'group_name'=>$name])->select();
				if(!$res->isEmpty()) $check = false;
				break;
			case '2':
				$res = Db::table('kt_wework_tag')->where(['wid'=>$wid,'tag_name'=>$name,'group_id'=>$group_id])->select();
				if(!$res->isEmpty()) $check = false;
				break;
		}

		return $check;
	}
	/**
	 * 同步企微标签
	 * @return 
	 */
	static public function sync(){
		$wid = Session::get('wid');
		$allTags = QyWechatApi::getCorpTagList();
		if($allTags['errcode']!=0) return 'error';
		if(count($allTags['tag_group']) == 0) return 'ok';
		$groupData = [];
		$data = [];
		$grouid = [];
		$tagid = [];
		foreach ($allTags['tag_group'] as $group) {
			$groupData[]=[
				'wid'=>$wid,
				'group_id'=>$group['group_id'],
				'group_name'=>$group['group_name'],
				'deleted'=>1,
				'order'=>$group['order'],
				'create_time'=>date("Y-m-d H:i:s",$group['create_time']),
				'web_order'=>$group['order'],
			];
			$grouid[] = $group['group_id'];
			foreach ($group['tag'] as $tag) {
				$data[] = [
					'wid'=>$wid,
					'group_id'=>$group['group_id'],
					'tag_id'=>$tag['id'],
					'tag_name'=>$tag['name'],
					'deleted'=>1,
					'order'=>$tag['order'],
					'create_time'=>date("Y-m-d H:i:s",$tag['create_time']),
					'web_order'=>$tag['order'],
				];
				$tagid[] = $tag['id'];
			}
		}
		$groupsql = Db::table('kt_wework_taggroup')->fetchSql(true)->insertAll($groupData);
		$groupsql .= ' ON DUPLICATE KEY UPDATE  group_name=VALUES(group_name),`order`=VALUES(`order`)';
		Db::execute($groupsql);   //执行插入
		Db::table('kt_wework_taggroup')->where('wid',$wid)->whereNotIn('group_id',$grouid)->update(['deleted'=>0]);  //不在此列表的更改为删除
		$tagsql = Db::table('kt_wework_tag')->fetchSql(true)->insertAll($data);
		$tagsql .= ' ON DUPLICATE KEY UPDATE tag_name=VALUES(tag_name),`order`=VALUES(`order`)';
		Db::execute($tagsql);
        Db::table('kt_wework_tag')->where('wid',$wid)->whereNotIn('tag_id',$tagid)->update(['deleted'=>0]);  //不在此列表的更改为删除  
		self::addWeborder();
		return 'ok';
	}
	//将标签编顺序
	static public function addWeborder(){
		$wid = Session::get('wid');
		$group = Db::table('kt_wework_taggroup')->field('id,group_id')->where('wid',$wid)->where('deleted',1)->where('web_order',0)->select();
		if($group->isEmpty()) return '';
		$maxGroupWeborder = Db::table('kt_wework_taggroup')->where('wid',$wid)->max('web_order');
		foreach ($group as  $g) {
			$maxGroupWeborder++;
			Db::table('kt_wework_taggroup')->where('id',$g['id'])->update(['web_order'=>$maxGroupWeborder]);
			$tag=Db::table('kt_wework_tag')->field('id')->where('wid',$wid)->where('deleted',1)->where('group_id',$g['group_id'])->select();
			$maxTag=Db::table('kt_wework_tag')->where('wid',$wid)->where('group_id',$g['group_id'])->max('web_order');
			if($tag->isEmpty()) continue;
			foreach ($tag as $t) {
				$maxTag++;
				Db::table('kt_wework_tag')->where('id',$t['id'])->update(['web_order'=>$maxTag]);
			}
		}
	}

}